<template>
  <div>
    <div style="margin: 10px 0">
      <el-input style="width: 200px" v-model="rname" placeholder="请输入名称" suffix-icon="el-icon-search"></el-input>
      <el-button class="ml-5" type="primary" @click="getPageData">搜索</el-button>
      <el-button type="warning" @click="reset">重置</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button @click="add" type="primary"><i style="margin-right: 5px" class="el-icon-circle-plus-outline"></i>新增
      </el-button>
      <el-button @click="batchDel" type="danger"><i style="margin-right: 5px" class="el-icon-remove-outline"></i>批量删除
      </el-button>
    </div>

    <el-table :data="tableData" border stripe :header-cell-class-name="headerBg"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column prop="id" label="ID" width="80px"></el-table-column>
      <el-table-column prop="rname" label="角色名"></el-table-column>
      <el-table-column prop="flag" label="唯一标识"></el-table-column>
      <el-table-column prop="description" label="描述"></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
          <el-button type="success" @click="Edit(scope.row)"><i class="el-icon-edit"
                                                                style="margin-right: 5px;width: 20px"></i>编辑
          </el-button>
          <el-button type="info" @click="selectMenu(scope.row.id)"><i class="el-icon-menu"
                                                                      style="margin-right: 5px;width: 10px"></i>分配菜单
          </el-button>
          <el-button type="danger" @click="Delete(scope.row.id)"><i class="el-icon-delete-solid"
                                                                    style="margin-right: 5px; width: 20px"></i>删除
          </el-button>
        </template>

      </el-table-column>
    </el-table>
    <div style="padding: 10px 0">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalCount">
      </el-pagination>
    </div>


    <el-dialog title="角色新增" :visible.sync="dialogFormVisible" width="30%">
      <el-form label-width="80px" size="small" :model="form" :rules="rules" ref="form">
        <el-form-item label="名称" prop="rname">
          <el-input v-model="form.rname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="菜单分配" :visible.sync="menuDialog" width="30%">
      <el-tree
          :data="menuData"
          :props="props"
          show-checkbox
          node-key="id"
          ref="tree"
          :default-expanded-keys="expanded"
          :default-checked-keys="checked"
      >
      </el-tree>
      <div slot="footer" class="dialog-footer">
        <el-button @click="menuDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleMenu">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="角色修改" :visible.sync="uDialogFormVisible" width="30%">
      <el-form label-width="80px" size="small" :model="form" :rules="rules" ref="form">
        <el-form-item label="名称" prop="rname">
          <el-input v-model="form.rname" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="uDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('form')">确 定</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
export default {
  name: "User",
  data() {
    return {
      totalCount: 0,
      pageNum: 1,
      pageSize: 5,
      rname: '',
      tableData: [],
      multipleSelection: [],
      menuDialog: false,
      dialogFormVisible: false,
      uDialogFormVisible: false,
      headerBg: 'headerBg',
      // 菜单树
      menuData: [],
      expanded: [],  // 默认展开的菜单id
      checked: [],   // 默认选中的菜单id
      roleId: 0,
      props: {
        label: 'mname',
      },
      form: {
        id: '',
        rname: '',
        description: '',
      },
      rules: {
        rname: [{required: true, message: '请输入角色名称', trigger: 'blur'}],
        description: [{required: false, message: '请输入描  述'}],
      },
    }
  },
  created() {
    // 请求分页查询数据
    this.getPageData()
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.getPageData();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.getPageData()
    },
    reset() {
      this.rname = "";
      this.getPageData()
    },
    add() {
      this.dialogFormVisible = true;
      this.form = {};
    },
    Edit(row) {
      this.form.id = row.id;
      this.form.rname = row.rname;
      this.form.description = row.description;
      this.uDialogFormVisible = true;
    },
    Delete(id) {
      this.$confirm('确定要删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.delete("/role/deleteById/" + id).then(res => {
          if (res.code === 1000) {
            this.$message({
              type: 'info',
              message: res.data
            });
            this.getPageData()
          } else {
            this.$message({
              type: 'info',
              message: res.data
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.request.post("/role/save", this.form)
              .then(res => {
                if (res.code === 1000) {
                  this.$message({
                    showClose: true,
                    message: res.data,
                    type: 'success'
                  });
                  this.dialogFormVisible = false;
                  this.uDialogFormVisible = false;
                  this.getPageData()
                } else {
                  this.$message({
                    showClose: true,
                    message: res.data,
                    type: 'error'
                  });
                  this.resetForm(formName)
                }
              })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },

    // 批量删除
    handleSelectionChange(val) {
      this.multipleSelection = [];
      this.multipleSelection = val;
    },
    batchDel() {
      // 下面这一句是将multipleSelection中的每一行的对象转换成纯id的数组
      let ids = this.multipleSelection.map(val => val.id)


      this.$confirm('确定要删除这些用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.request.post("/role//batchDelete", ids)
            .then(res => {
              if (res.code === 1000) {
                this.$message({
                  showClose: true,
                  message: res.data,
                  type: 'success'
                });
              }
              this.getPageData()
            })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    selectMenu(roleId) {
      this.menuDialog = true;
      this.roleId = roleId;
      this.request.get("/menu/findAll", {})
          .then(res => {
            this.menuData = []
            this.checked = []
            this.menuData = res.data

            // 把后台返回的菜单数据转换成对应的id
            this.expanded = this.menuData.map(x => x.id)

            this.request.get("/role/roleMenu/" + this.roleId)
                .then(res => {
                  this.checked = res.data

                  this.request.get("/menu/ids", {})
                  .then(res => {
                    const ids = res.data
                    ids.forEach(id => {
                      if(!this.checked.includes(id)){
                        this.$nextTick(()=>{
                          this.$refs.tree.setChecked(id,false)
                        })
                      }
                    })
                    this.menuDialog = true
                  })
                })

          })
    },


    saveRoleMenu() {
      this.request.post("/role/roleMenu/" + this.roleId, this.$refs.tree.getCheckedKeys())
          .then(res => {
            if (res.code === 1000) {
              this.$message.success("分配成功")
              this.menuDialog = false
              let user = localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : ""
              if(user.role === "管理员"){
                this.$store.commit("resetUser")
                setTimeout(()=>{
                  this.$message.success("请重新登录")
                },3000)
              }

            } else {
              this.$message.error(res.msg)
            }
          })
    },


    // 获取分页查询数据
    getPageData() {
      this.request.get("/role/page", {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          rname: this.rname,
        }
      })
          .then(res => {
            this.tableData = []
            this.tableData = res.data.data
            this.totalCount = res.data.totalCount
          })
    }
  }
}
</script>


<style>
.headerBg {
  background: #eee !important;
}
</style>